﻿using System;
using System.Web;
using br.com.SistemaChamados.Constants;
using br.com.SistemaChamados.Controller;
using br.com.SistemaChamados.Controller.Common;
using br.com.SistemaChamados.Enum;
using br.com.SistemaChamados.Model;
using br.com.SistemaChamados.Model.Common;
using br.com.SistemaChamados.Util;


namespace SistemaChamados.Pages.Common
{
    public partial class Login : System.Web.UI.Page
    {
        private const string PROFILE_ROOT = "ADMIN";
        //private const string PROFILE_ROOT_WELCOME_PAGE = "../Category/CallCategoryMain.aspx";
        private const string PROFILE_ROOT_WELCOME_PAGE = "../Main/mainAdmin.aspx";
        private const string PROFILE_USER = "USER";
        private const string PROFILE_USER_WELCOME_PAGE = "../Main/mainUser.aspx";
        private const string PROFILE_ANALYST = "ANALYST";
        private const string PROFILE_ANALYST_WELCOME_PAGE = "../Main/mainAnalyst.aspx";
        private const string PROFILE_TECHNICAL = "TECHNICAL";
        private const string PROFILE_TECHNICAL_WELCOME_PAGE = "../Main/mainTechnical.aspx";
       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                imgCaptcha.ImageUrl = "Captcha.aspx";
            }
            if (!IsPostBack)
            {
                if (ddlUnit.Items.Count < 1)
                {
                    FillDdlUnit();
                }
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            br.com.SistemaChamados.Model.Common.User user =
           new br.com.SistemaChamados.Model.Common.User();
            user.EMail = txbLogin.Text;
            user.Password = txbPassword.Text;
            UserController userController = new UserController();
            //try
            //{
                if (userController.validateUser(ref user) == EnumUserState.USER_STATE_LOGGED_IN)
                {
                    Response.Cookies.Add(SecurityUtils.createATicketValidation(user));
                    Session[UserConstants.SESSION_USER_LOGGED_IN] = user.Id;
                    Response.Redirect("../Main/Main.aspx");
                }
                else
                {
                    Response.Write(@"<script language='javascript'>alert('Usuário inexistente!');</script>");
                }
            //}
            //catch (Exception ex)
            //{
            //    string temp = ex.Message;
            //    Response.Write(@"<script language='javascript'>alert('Ocorreu um erro ao validar o login: <br>" + ex.Message +
            //                   ".');</script>");
            //    user = null;
            //}
        }

        protected void btnInserir_Click(object sender, EventArgs e)
        {
            if (validateCaptcha())
            {
                User user = new User();
                try
                {
                    //Tirar os hard coded
                    user.EMail = Convert.ToString(txbEMail.Text);
                    user.Password = Convert.ToString(txbSignUpPassword.Text);
                    user.Name = Convert.ToString(txbName.Text);
                    user.Profile = "USER";
                    Sector sector = new Sector();
                    sector.Id = Convert.ToInt32(ddlSector.SelectedValue);
                    // USER, ANALYST, TECHNICAL,ADMIN
                    user.Sector = sector;
                    tryInsert(user);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('A sequência de caracteres digitada não coincide com a da imagem.');</script>");
            }
        }

        private void tryInsert(User userInsert)
        {
            UserController controller = new UserController();
            try
            {
                if (controller.InsertUser(userInsert) == EnumGenericState.GENERIC_STATE_SUCCESS)
                {
                    Response.Write(@"<script language='javascript'>alert('Pessoa Cadastrada com Sucesso!');</script>");
                    ClearFields();
                    ClearDdlSector();
                }
                else
                {
                    Response.Write(@"<script language='javascript'>alert('Ocorreu um erro durante o cadastro, por favor tente novamente!');</script>");
                }
            }
            catch (Exception ex)
            {
                Response.Write(@"<script language='javascript'>alert('Ocorreu um erro no cadastro: <br>" + ex.Message +
                                   ".');</script>");
                userInsert = null;
            }
        }

        private void ClearFields()
        {
            txbName.Text = "";
            txbEMail.Text = "";
            txbPassword.Text = "";
            txbPasswordValidate.Text = "";
            txbName.Focus();
        }

        private void FillDdlUnit()
        {
            UnitController unitController = new UnitController();
            ddlUnit.DataSource = unitController.GetUnits();
            ddlUnit.DataTextField = "Name";
            ddlUnit.DataValueField = "Id";
            ddlUnit.DataBind();
            ddlUnit.Items.Insert(0, "Selecione");
        }
        protected void ddlUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillDdlSector();
        }

        private void ClearDdlSector()
        {
            for (int i = 0; i < ddlSector.Items.Count; i++)
            {
                ddlSector.Items[i].Selected = false;
            }
            ddlSector.Items[0].Selected = true;
            ddlSector.DataSource = "";
            ddlSector.DataBind();
        }

        private void FillDdlSector()
        {
            SectorController sectorController = new SectorController();
            br.com.SistemaChamados.Model.Unit unit = new br.com.SistemaChamados.Model.Unit();
            Sector sector = new Sector();
            if (Convert.ToInt32(ddlUnit.SelectedIndex) > 0)
            {
                unit.Id = Convert.ToInt32(ddlUnit.SelectedValue);
                sector.Unit = unit;
                ddlSector.DataSource = sectorController.ListSectorByUnit(sector);
                ddlSector.DataTextField = "Description";
                ddlSector.DataValueField = "Id";
                ddlSector.DataBind();
                ddlSector.Items.Insert(0, "Selecione");
            }
            else
            {
                ClearDdlSector();
            }

        }

        private static void redirectToWelcomePage(string profile, HttpResponse response)
        {
            switch (profile)
            {
                case PROFILE_ROOT:
                    response.Redirect(PROFILE_ROOT_WELCOME_PAGE);
                    break;
                case PROFILE_ANALYST:
                    response.Redirect(PROFILE_ANALYST_WELCOME_PAGE);
                    break;
                case PROFILE_TECHNICAL:
                    response.Redirect(PROFILE_TECHNICAL_WELCOME_PAGE);
                    break;
                case PROFILE_USER:
                    response.Redirect(PROFILE_USER_WELCOME_PAGE);
                    break;
            }
        }

        private bool validateCaptcha()
        {
            string strCaptcha = txtCaptcha.Text;
            if (Session["CaptchaImageText"].ToString() == strCaptcha)
                return true;
            else
                return false;
        }
    }
}